package ngat.oss;

import ngat.message.OSS.*;
import ngat.util.*;
import ngat.util.logging.*;
import ngat.phase2.*; 
import ngat.instrument.*;
import ngat.phase2.nonpersist.*;

import java.io.*;
import java.lang.reflect.*;

import jyd.dbms.*;
import jyd.storable.*;
import jyd.collection.*;

/**
 * Action: Sent by ADMIN to add a User. 
 * @author S.N.Fraser
 * $Id: ADD_USERImpl.java,v 1.1 2006/11/27 08:45:00 snf Exp $
 */
public class ADD_USERImpl extends TransactionImpl {
    
    /** The path used to locate the User's Tag in the OSS database. */
    protected Path tagPath;
    
    /** The User data to insert at 'tagPath'.*/
    protected User user;
    
    /** The password for this User. */
    protected String password;
    
    public ADD_USERImpl(Path tagPath, User user, String password) {
	super();
	this.tagPath = tagPath;
	this.user = user;
	this.password = password;
    }
    
    public ADD_USERImpl(ADD_USER request) throws InvocationTargetException {
	super(request);
	this.tagPath  = request.getTagPath();	
	this.user     = request.getUser();
	this.password = request.getPassword();
    }

    /**
     * Places the User in the DB and updates the OSS password table..
     * @return Boolean or an OSS_Error.
     */
    public TRANSACTION_DONE exec() { 
	
	Tag tag = null;
	
	Transaction t = null;
	try {
	    t = Transaction.current();
 
	    // Locate the User's owner (Tag) from its path expression.
	    tag = OSS_Utilities.fetchTag(tagPath);
	   
	    // Check if Tag exists.
	    if (tag == null) {
		logger.log(1, "ADDUSER_Impl", id, "exec",
			   "Tag: "+tagPath.toString()+" Not in database.");
		return error(TRANSACTION.PATH_RESOLUTION_ERROR,
				     "Could not find User's Tag: "
				     +tagPath.toString());
	    }

	    // Update the password table.
	    try {
		String userkey = tagPath.toString()+"/"+user.getName();
		System.err.println("ADD_USER: Rdy Insert entry:  Userpath: "+userkey+ " Pass: "+password);
		ServerContext.insertPasswordTableEntry(userkey, password);
		logger.log(1, "ADDUSER_Impl", id, "exec",
			   "Inserted PWT entry for: "+userkey);
	    } catch (ServerEnvException sex) {
		logger.log(1, "ADDUSER_Impl", id, "exec",
			   "Error Updating Password Table: "+sex);
		return error(TRANSACTION.PASSWORD_TABLE_ERROR, 
				     "Password Table Update: "+sex);
	    }
	    
	    // Slot the User in.
	    tag.addUser(user);
	    
	    ADD_USER_DONE done = new ADD_USER_DONE(id);
	    done.setSuccessful(true);
	    return done;

	} finally {
	    t.commit();
	}
	
    }
    
}

/** $Log: ADD_USERImpl.java,v $
/** Revision 1.1  2006/11/27 08:45:00  snf
/** Initial revision
/**
/** Revision 1.2  2001/04/27 17:22:00  snf
/** Adda proposal.
/**
/** Revision 1.1  2001/02/23 18:51:14  snf
/** Initial revision
/**
/** Revision 1.1  2001/02/20 10:29:16  snf
/** Initial revision
/**
/** Revision 1.1  2000/12/12 18:18:32  snf
/** Initial revision
/** */
